//
//  YZMStockSellView.m
//  YZMicroStock
//
//  Created by wangminhong on 16/3/28.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMStockSellView.h"
#import "YZMStockSellCell.h"
#import "YZMAlertView.h"
#import "YZMResultView.h"
#import "YZMPageService.h"
#import "YZClient.h"
#import "YZMSaleTradePacket.h"
#import "YZMSaleTradeModel.h"
#import "YZMStockRealModel.h"
#import "NSNumber+Utils.h"
#import "UILabel+Color.h"
#import "YZMStockSellHeader.h"
#import "YZMWebViewService.h"
#import "YZMConfigureService.h"
#import <DateTools/DateTools.h>
#import <BlocksKit/UIControl+BlocksKit.h>
#import <MJRefresh/MJRefresh.h>
#import "YZMStockSellNoneCell.h"
#import "YZMStockSellNewCell.h"
#import "YZMStockViewController.h"
#import "YZMOneyuanViewController.h"
#import "YZMSimulateViewController.h"
#import "YZMDelayCharge.h"
#import "YZMFreeExperienceViewController.h"
#import "YZClient+FreeExperience.h"
#import "YZMSaleTradePacket.h"

static NSString *const sYZMStockSellCellID = @"YZMStockSellCellID";
static NSString *const sYZMStockSellHeaderID = @"YZMStockSellHeaderID";
static NSString *const sYZMStockSellNoneCellID = @"YZMyStockSellNoneCellID";
static NSString *const sYZMStockSellNewCellID=@"sYZMStockSellNewCellID";

@interface YZMStockSellView()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *dataList;
@property (nonatomic, strong) MJRefreshNormalHeader *refreshHeader;
@property (nonatomic, strong) YZMResultView *resultView;
@property (nonatomic, strong) YZMPageService *pageService;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) NSTimer *profitTimer;
@property (nonatomic, strong) NSMutableDictionary *realDataDict;
@property (nonatomic, assign) BOOL firstFetchFlag;
@property (nonatomic, assign) double totalMoney;
@property (nonatomic, assign) double expireMoney;
@property (nonatomic, assign) CGFloat headerHeight;
@property (nonatomic, assign) BOOL inTimeFlag;//保存交易时间段标志位
@property (nonatomic, assign) BOOL inTimeShowFlag;//保存递延费显示标志位
@property (nonatomic, assign) BOOL unShowErrorFlag;//不显示错误标志位
@property (nonatomic, assign) YZM_TRADE_TYPE tradeType;
@property (nonatomic, assign) double bottomValue;
@property (nonatomic, strong) YZMConfigureService *service;
@end

@implementation YZMStockSellView

-(instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style andTradeType:(YZM_TRADE_TYPE)tradeType
{
    self = [super initWithFrame:frame style:style];
    if (self) {

        _tradeType = tradeType;
        self.service = [YZMConfigureService sharedServiceWithTradeType:_tradeType];
        self.backgroundColor = [YZMAppStyle appBackgroundColor];
        self.dataList = [NSMutableArray array];
        self.realDataDict = [NSMutableDictionary dictionary];
        self.pageService = [YZMPageService new];
        self.pageService.pageSize = 100;
        self.dataSource = self;
        self.delegate = self;
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self registerClass:[YZMStockSellCell class] forCellReuseIdentifier:sYZMStockSellCellID];
        [self registerClass:[YZMStockSellHeader class] forHeaderFooterViewReuseIdentifier:sYZMStockSellHeaderID];
        [self registerClass:[YZMStockSellNoneCell class] forCellReuseIdentifier:sYZMStockSellNoneCellID];
        [self registerClass:[YZMStockSellNewCell class] forCellReuseIdentifier:sYZMStockSellNewCellID];
        
        self.refreshHeader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self stopTimer];
            [self startTimer];
        }];
        self.refreshHeader.stateLabel.textColor = [YZMAppStyle colorForLightGrayText];
        self.refreshHeader.stateLabel.font = [YZMAppStyle mediumSizeFont];
        self.refreshHeader.lastUpdatedTimeLabel.hidden = YES;
        
        self.mj_header = self.refreshHeader;
        
        self.estimatedRowHeight = 0;
        self.estimatedSectionHeaderHeight = 0;
        self.estimatedSectionFooterHeight = 0;
        
        self.resultView = [YZMResultView new];
        self.resultView.backgroundColor = [YZMAppStyle appBackgroundColor];
        [self addSubview:self.resultView];
        [self.resultView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.width.height.equalTo(self);
        }];
        
        __weak __typeof(&*self) weakSelf = self;
        self.resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
        self.resultView.retryAction = ^(){
            
            [weakSelf stopTimer];
            [weakSelf startTimer];
        };
    }
    return self;
}


#pragma mark -- ui

- (YZMAlertView *)alertViewForStockSellMakeSureWithStock:(YZMSaleTradeModel *)stock andStockReal:(YZMStockRealModel*)stockReal andClickAction:(void (^)(BOOL selectdFlag))clickAction{
    YZMAlertView *alertView = [YZMAlertView new];
    alertView.titleLabel.text = @"点卖确认";
    
    UIView *customView = [UIView new];
    
    UIView *leftView = [UIView new];
    NSArray *leftArray = @[@"股票名称：", @"股票代码：",@"委托价格：",@"卖出数量：",@"持仓天数：",@"浮动盈亏："];
    
    UIView *lastView = nil;
    for (NSString *title in leftArray) {
        
        UILabel *label = [YZMAppStyle labelWithMediumGray];
        label.text = title;
        [leftView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(leftView);
            make.right.lessThanOrEqualTo(leftView);
            if (lastView) {
                make.top.equalTo(lastView.mas_bottom).offset(15);
            }else{
                make.top.equalTo(leftView);
            }
        }];
        
        lastView = label;
    }
    
    [leftView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(lastView);
    }];
    
    UIView *rightView = [UIView new];
    double profit = (stockReal.price - stock.buyPriceDeal)*stock.holdCount;
    NSArray *rightArray = @[stock.stockName, [stock.stockCode substringFromIndex:2],@"市价",[NSString stringWithFormat:@"%@股",@(stock.holdCount)],[NSString stringWithFormat:@"%@天",@(stock.holdDays)],[NSString stringWithFormat:@"%@元", @(profit).p02fString]];
    
    lastView = nil;
    for (NSString *title in rightArray) {
        
        UILabel *label = [YZMAppStyle labelWithMediumGray];
        label.text = title;
        if (title == rightArray.lastObject) {
            
            [label setTextColorWithGreatNumber:profit andSmallNumber:0.0];
        }
        [rightView addSubview:label];
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(rightView);
            make.left.greaterThanOrEqualTo(rightView);
            if (lastView) {
                make.top.equalTo(lastView.mas_bottom).offset(15);
                
            }else{
                make.top.equalTo(rightView);
            }
        }];
        
        lastView = label;
    }
    
    [rightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(lastView);
    }];
    
    [customView addSubview:leftView];
    [leftView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(customView);
    }];
    
    [customView addSubview:rightView];
    [rightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.equalTo(customView);
    }];
    
    UIButton *delayBT = [UIButton new];
    delayBT.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
    delayBT.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [delayBT setImage:[UIImage imageNamed:@"icon_choose_button"] forState:UIControlStateNormal];
    [delayBT setImage:[UIImage imageNamed:@"icon_choose_button_redselected"] forState:UIControlStateSelected];
    delayBT.selected = YES;
    [delayBT setTitle:@" 是否递延指令" forState:UIControlStateNormal];
    [delayBT setTitleColor:[YZMAppStyle colorForBlackText] forState:UIControlStateNormal];
    delayBT.titleLabel.font=[YZMAppStyle smallSizeFont];
    [delayBT bk_addEventHandler:^(id sender) {
        UIButton *bt = (UIButton *)sender;
        bt.selected = !bt.selected;
    } forControlEvents:UIControlEventTouchUpInside];
    
    [customView addSubview:delayBT];
    [delayBT mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(leftView.mas_bottom).offset(28);
        make.left.right.equalTo(customView);
    }];
    
    UILabel *recommandLB = [YZMAppStyle labelWithFont:[YZMAppStyle smallSizeFont] andColor:[YZMAppStyle colorForGrayText]];
    recommandLB.text = @"注:点卖指令可能因跌停导致无法成交，默认至下一个交易日挂单交易。浮动盈亏仅供参考，具体以实际成交为准。";
    recommandLB.numberOfLines = 0;
    [delayBT addSubview:recommandLB];
    [recommandLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(delayBT);
        make.top.equalTo(delayBT.mas_bottom).offset(2);
        make.right.equalTo(customView);
        make.bottom.mas_equalTo(customView.mas_bottom);
    }];
    
    if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_ONE) {

        delayBT.hidden=YES;
        recommandLB.hidden=YES;
        [customView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(leftView.mas_bottom);
        }];
    }else if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_FREE || self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_YLB){
        delayBT.hidden=YES;
        recommandLB.hidden=YES;
        [customView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(leftView.mas_bottom);
        }];
    }
    
    alertView.customView = customView;
    alertView.confirmHandle = ^(){
        if (clickAction) {
            clickAction(delayBT.selected);
        }
        return YES;
    };
    return alertView;
}

- (YZMAlertView *)alertViewForStockSellMakeSureWithStockTradePacket:(YZMSaleTradePacket *)stock andStockReal:(YZMStockRealModel*)stockReal andClickAction:(void (^)(BOOL selectdFlag))clickAction{
    YZMAlertView *alertView = [YZMAlertView new];
    alertView.titleLabel.text = @"点卖确认";
    
    UIView *customView = [UIView new];
    
    UIView *leftView = [UIView new];
    NSArray *leftArray = @[@"股票名称：", @"股票代码：",@"委托价格：",@"卖出数量：",@"浮动盈亏："];
    
    UIView *lastView = nil;
    for (NSString *title in leftArray) {
        
        UILabel *label = [YZMAppStyle labelWithMediumGray];
        label.text = title;
        [leftView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(leftView);
            make.right.lessThanOrEqualTo(leftView);
            if (lastView) {
                make.top.equalTo(lastView.mas_bottom).offset(15);
            }else{
                make.top.equalTo(leftView);
            }
        }];
        
        lastView = label;
    }
    
    [leftView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(lastView);
    }];
    
    UIView *rightView = [UIView new];
    double profit = (stockReal.price - [stock.realBuyPrice doubleValue])*stock.holdNum;
    NSArray *rightArray = @[stock.stockName, [stock.stockCode substringFromIndex:2],@"市价",[NSString stringWithFormat:@"%@股",@(stock.holdNum)],[NSString stringWithFormat:@"%@元", @(profit).p02fString]];
    
    lastView = nil;
    for (NSString *title in rightArray) {
        
        UILabel *label = [YZMAppStyle labelWithMediumGray];
        label.text = title;
        if (title == rightArray.lastObject) {
            
            [label setTextColorWithGreatNumber:profit andSmallNumber:0.0];
        }
        [rightView addSubview:label];
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(rightView);
            make.left.greaterThanOrEqualTo(rightView);
            if (lastView) {
                make.top.equalTo(lastView.mas_bottom).offset(15);
                
            }else{
                make.top.equalTo(rightView);
            }
        }];
        
        lastView = label;
    }
    
    [rightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(lastView);
    }];
    
    [customView addSubview:leftView];
    [leftView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(customView);
    }];
    
    [customView addSubview:rightView];
    [rightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.equalTo(customView);
    }];
    
    UIButton *delayBT = [UIButton new];
    delayBT.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
    delayBT.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [delayBT setImage:[UIImage imageNamed:@"icon_choose_button"] forState:UIControlStateNormal];
    [delayBT setImage:[UIImage imageNamed:@"icon_choose_button_redselected"] forState:UIControlStateSelected];
    delayBT.selected = YES;
    [delayBT setTitle:@" 是否递延指令" forState:UIControlStateNormal];
    [delayBT setTitleColor:[YZMAppStyle colorForBlackText] forState:UIControlStateNormal];
    delayBT.titleLabel.font=[YZMAppStyle smallSizeFont];
    [delayBT bk_addEventHandler:^(id sender) {
        UIButton *bt = (UIButton *)sender;
        bt.selected = !bt.selected;
    } forControlEvents:UIControlEventTouchUpInside];
    
    [customView addSubview:delayBT];
    [delayBT mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(leftView.mas_bottom).offset(28);
        make.left.right.equalTo(customView);
    }];
    
    UILabel *recommandLB = [YZMAppStyle labelWithFont:[YZMAppStyle smallSizeFont] andColor:[YZMAppStyle colorForGrayText]];
    recommandLB.text = @"注:点卖指令可能因跌停导致无法成交，默认至下一个交易日挂单交易。浮动盈亏仅供参考，具体以实际成交为准。";
    recommandLB.numberOfLines = 0;
    [delayBT addSubview:recommandLB];
    [recommandLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(delayBT);
        make.top.equalTo(delayBT.mas_bottom).offset(2);
        make.right.equalTo(customView);
        make.bottom.mas_equalTo(customView.mas_bottom);
    }];
    
    if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_ONE) {
        
        delayBT.hidden=YES;
        recommandLB.hidden=YES;
        [customView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(leftView.mas_bottom);
        }];
    }else if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_FREE){
        delayBT.hidden=YES;
        recommandLB.hidden=YES;
        [customView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(leftView.mas_bottom);
        }];
    }
    
    alertView.customView = customView;
    alertView.confirmHandle = ^(){
        if (clickAction) {
            clickAction(delayBT.selected);
        }
        return YES;
    };
    return alertView;
}


#pragma mark -- network

- (void)endRefresh{
    if (_refreshHeader.isRefreshing) {
        [_refreshHeader endRefreshing];
    }
}

- (void)fetchItemList{
    /*无网处理*/
    if (kNetworkNotReachability) {
        [self endRefresh];
        if ( self.dataList.count == 0) {
            self.resultView.status = YZM_RESULT_STATUS_FOR_NO_WIFI;
            self.mj_header = nil;
        }else{
            [NSError yz_showMessageForNoWifi];
        }
        return;
    }
    if (self.firstFetchFlag) {
        
        [YZClient td_fetchSaleTradeListWithPage:self.pageService.minPage andPageSize:self.pageService.pageSize andTimeEnd:_pageService.tempTimeEnd success:^(NSURLResponse *response, id responseObject) {
            [self endRefresh];
            self.mj_header = _refreshHeader;
            self.resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
            
            YZGeneralResultModel *topModel = responseObject;
            if (topModel.success) {
                YZMSaleTradePacket *result = topModel.data;
            
                self.totalMoney = result.tradingDeferCharge;
                self.expireMoney = result.unHanldHoldDeferCharge;
                self.headerHeight = [YZMStockSellHeader getHeightOfSelfTotalMoney:self.totalMoney andExpireMoney:self.expireMoney];
                if ([@(self.totalMoney) isGreaterThanDouble:0.0] && self.service.isInTradeShowTimePeriods) {
                    self.inTimeShowFlag = YES;
                }else{
                    self.inTimeShowFlag = NO;
                }
                
                NSArray *sList = result.items;
                [self.dataList removeAllObjects];
                [self.dataList addObjectsFromArray:sList];
                [self reloadData];
                
                [_pageService effectChange];
                
                if (self.dataList.count != 0) {
                    [self fetchStockDetailInfo];
                }
                _unShowErrorFlag=NO;
            }
            else{
                if (!_unShowErrorFlag) {
                if (self.dataList.count == 0) {
                    [_resultView syncStatusWithError:[NSError yz_errorWithMessage:topModel.resultMessage]];
                    self.mj_header = nil;
                }else{
                        [topModel showMessage];
                    }
                }
                self.unShowErrorFlag = YES;
            }
        } failure:^(NSError *error) {
            [self endRefresh];
            if (!_unShowErrorFlag) {
                //网络异常处理
                if (self.dataList.count == 0) {
                    [_resultView syncStatusWithError:error];
                    self.mj_header = nil;
                }else{
                    [error yz_showMessage];
                }
            }
            _unShowErrorFlag = YES;
        }];
    }else{
        [YZClient td_fetchSaleTradeListOfMemcacheWithPage:self.pageService.minPage andPageSize:self.pageService.pageSize andTimeEnd:_pageService.tempTimeEnd success:^(NSURLResponse *response, id responseObject) {
            
            [self endRefresh];
            
            self.mj_header = _refreshHeader;
            self.resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
            
            YZGeneralResultModel *topModel = responseObject;
            if (topModel.success) {
                YZMSaleTradePacket *result = topModel.data;
                self.totalMoney = result.tradingDeferCharge;
                self.expireMoney = result.unHanldHoldDeferCharge;
                
                if ([@(self.totalMoney) isGreaterThanDouble:0.0] && self.service.isInTradeShowTimePeriods) {
                    
                    self.inTimeShowFlag = YES;
                }else{
                    self.inTimeShowFlag = NO;
                }
                
                NSArray *sList = result.items;
                [self.dataList removeAllObjects];
                [self.dataList addObjectsFromArray:sList];
                [self reloadData];
                
                [_pageService effectChange];
                if (self.dataList.count != 0) {
                    
                    [self fetchStockDetailInfo];
                }
                _unShowErrorFlag=NO;
            }
            else{
                if (!_unShowErrorFlag) {
                 if (self.dataList.count == 0) {
                    [_resultView syncStatusWithError:[NSError yz_errorWithMessage:topModel.resultMessage]];
                    self.mj_header = nil;
                }else{
                        [topModel showMessage];
                    }
                }
                self.unShowErrorFlag = YES;
            }
        } failure:^(NSError *error) {
            [self endRefresh];
             if (!_unShowErrorFlag) {
                //网络异常处理
                if (self.dataList.count == 0) {
                    [_resultView syncStatusWithError:error];
                    self.mj_header = nil;
                }else{
                    [error yz_showMessage];
                }
             }
            self.unShowErrorFlag = YES;
        }];
    }
    self.firstFetchFlag = NO;
}


- (void)fetchItemYlbList{
    /*无网处理*/
    if (kNetworkNotReachability) {
        [self endRefresh];
        if ( self.dataList.count == 0) {
            self.resultView.status = YZM_RESULT_STATUS_FOR_NO_WIFI;
            self.mj_header = nil;
        }else{
            [NSError yz_showMessageForNoWifi];
        }
        return;
    }
    if (self.firstFetchFlag) {
        
        [YZClient td_fetchSaleTradeYLbListWithPage:self.pageService.minPage andPageSize:self.pageService.pageSize andTimeEnd:_pageService.tempTimeEnd success:^(NSURLResponse *response, id responseObject) {
            [self endRefresh];
            self.mj_header = _refreshHeader;
            self.resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
            
            YZGeneralResultModel *topModel = responseObject;
            if (topModel.success) {
                YZMSaleTradePacket *result = topModel.data;
                
                self.totalMoney = result.tradingDeferCharge;
                self.expireMoney = result.unHanldHoldDeferCharge;
                
                if ([@(self.totalMoney) isGreaterThanDouble:0.0] && self.service.isInTradeShowTimePeriods) {
                    self.inTimeShowFlag = YES;
                }else{
                    self.inTimeShowFlag = NO;
                }
                
                NSArray *sList = result.items;
                [self.dataList removeAllObjects];
                [self.dataList addObjectsFromArray:sList];
                [self reloadData];
                
                [_pageService effectChange];
                
                if (self.dataList.count != 0) {
                    [self fetchStockDetailInfo];
                }
                _unShowErrorFlag=NO;
            }
            else{
                if (!_unShowErrorFlag) {
                    if (self.dataList.count == 0) {
                        [_resultView syncStatusWithError:[NSError yz_errorWithMessage:topModel.resultMessage]];
                        self.mj_header = nil;
                    }else{
                        [topModel showMessage];
                    }
                }
                self.unShowErrorFlag = YES;
            }
        } failure:^(NSError *error) {
            [self endRefresh];
            if (!_unShowErrorFlag) {
                //网络异常处理
                if (self.dataList.count == 0) {
                    [_resultView syncStatusWithError:error];
                    self.mj_header = nil;
                }else{
                    [error yz_showMessage];
                }
            }
            _unShowErrorFlag = YES;
        }];
    }else{
        [YZClient td_fetchSaleTradeYlbListOfMemcacheWithPage:self.pageService.minPage andPageSize:self.pageService.pageSize andTimeEnd:_pageService.tempTimeEnd success:^(NSURLResponse *response, id responseObject) {
            
            [self endRefresh];
            
            self.mj_header = _refreshHeader;
            self.resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
            
            YZGeneralResultModel *topModel = responseObject;
            if (topModel.success) {
                YZMSaleTradePacket *result = topModel.data;
                self.totalMoney = result.tradingDeferCharge;
                self.expireMoney = result.unHanldHoldDeferCharge;
                
                if ([@(self.totalMoney) isGreaterThanDouble:0.0] && self.service.isInTradeShowTimePeriods) {
                    
                    self.inTimeShowFlag = YES;
                }else{
                    self.inTimeShowFlag = NO;
                }
                
                NSArray *sList = result.items;
                [self.dataList removeAllObjects];
                [self.dataList addObjectsFromArray:sList];
                [self reloadData];
                
                [_pageService effectChange];
                if (self.dataList.count != 0) {
                    
                    [self fetchStockDetailInfo];
                }
                _unShowErrorFlag=NO;
            }
            else{
                if (!_unShowErrorFlag) {
                    if (self.dataList.count == 0) {
                        [_resultView syncStatusWithError:[NSError yz_errorWithMessage:topModel.resultMessage]];
                        self.mj_header = nil;
                    }else{
                        [topModel showMessage];
                    }
                }
                self.unShowErrorFlag = YES;
            }
        } failure:^(NSError *error) {
            [self endRefresh];
            if (!_unShowErrorFlag) {
                //网络异常处理
                if (self.dataList.count == 0) {
                    [_resultView syncStatusWithError:error];
                    self.mj_header = nil;
                }else{
                    [error yz_showMessage];
                }
            }
            self.unShowErrorFlag = YES;
        }];
    }
    self.firstFetchFlag = NO;
}


- (void)fetchItemListforD{
    /*无网处理*/
    if (kNetworkNotReachability) {
        [self endRefresh];
        if ( self.dataList.count == 0) {
            self.resultView.status = YZM_RESULT_STATUS_FOR_NO_WIFI;
            self.mj_header = nil;
        }else{
            [NSError yz_showMessageForNoWifi];
        }
        return;
    }
    if (self.firstFetchFlag) {
        [YZClient td_fetchSaleTradeListForDsuccess:^(NSURLResponse *response, id responseObject) {
            [self endRefresh];
            self.mj_header = _refreshHeader;
            self.resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
            
            YZGeneralResultModel *topModel = responseObject;
            if (topModel.success) {
                
                NSArray *array =  topModel.data;
                [self.dataList removeAllObjects];
                for (NSDictionary *dic in array) {
                    YZMSaleTradeModel *model=  (YZMSaleTradeModel *)dic;
                    [self.dataList addObject:model];
                }
    
                [self reloadData];
                [_pageService effectChange];
                
                if (self.dataList.count == 0) {
                    self.bottomLabel.hidden = YES;
                } else {
                    self.bottomLabel.hidden = NO;
                    [self fetchStockDetailInfo];
                }
                _unShowErrorFlag=NO;
            }
            else{
                if (!_unShowErrorFlag) {
                    if (self.dataList.count == 0) {
                        self.bottomLabel.hidden = YES;
                        [_resultView syncStatusWithError:[NSError yz_errorWithMessage:topModel.resultMessage]];
                        self.mj_header = nil;
                    }else{
                        [topModel showMessage];
                    }
                }
                self.unShowErrorFlag = YES;
            }
        } failure:^(NSError *error) {
            [self endRefresh];
            if (!_unShowErrorFlag) {
                //网络异常处理
                if (self.dataList.count == 0) {
                    self.bottomLabel.hidden = YES;
                    [_resultView syncStatusWithError:error];
                    self.mj_header = nil;
                }else{
                    [error yz_showMessage];
                }
            }
            self.unShowErrorFlag = YES;
        }];
    }else{
        
        [YZClient td_fetchSaleTradeListForDOfMemcachesuccess:^(NSURLResponse *response, id responseObject) {
            [self endRefresh];
            self.mj_header = _refreshHeader;
            self.resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
            
            YZGeneralResultModel *topModel = responseObject;
            if (topModel.success) {
                NSArray *array =  topModel.data;
                [self.dataList removeAllObjects];
                for (NSDictionary *dic in array) {
                    YZMSaleTradeModel *model=  (YZMSaleTradeModel *)dic;
                    [self.dataList addObject:model];
                }
                [self reloadData];
                [_pageService effectChange];
                if (self.dataList.count == 0) {
                    self.bottomLabel.hidden = YES;
                } else {
                    self.bottomLabel.hidden = NO;
                    [self fetchStockDetailInfo];
                }
                _unShowErrorFlag=NO;
            }else{
                if (!_unShowErrorFlag) {
                    if (self.dataList.count == 0) {
                        self.bottomLabel.hidden = YES;
                        [_resultView syncStatusWithError:[NSError yz_errorWithMessage:topModel.resultMessage]];
                        self.mj_header = nil;
                    }else{
                        [topModel showMessage];
                    }
                }
                self.unShowErrorFlag = YES;
            }
        } failure:^(NSError *error) {
            [self endRefresh];
            if (!_unShowErrorFlag) {
                //网络异常处理
                if (self.dataList.count == 0) {
                    self.bottomLabel.hidden = YES;
                    [_resultView syncStatusWithError:error];
                    self.mj_header = nil;
                }else{
                    [error yz_showMessage];
                }
            }
            self.unShowErrorFlag = YES;
        }];
    }
    self.firstFetchFlag = NO;
}

- (void)fetchItemListforOneYuan{
    /*无网处理*/
    if (kNetworkNotReachability) {
        [self endRefresh];
        if ( self.dataList.count == 0) {
            self.resultView.status = YZM_RESULT_STATUS_FOR_NO_WIFI;
            self.mj_header = nil;
        }else{
            [NSError yz_showMessageForNoWifi];
        }
        return;
    }
    if (self.firstFetchFlag) {
        [YZClient oneY_getSaleListFirstWithParamsuccess:^(NSURLSessionDataTask *task, id responseObject) {
            [self endRefresh];
            self.mj_header = _refreshHeader;
            self.resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
            
            YZGeneralResultModel *topModel = responseObject;
            if (topModel.success) {
                
                YZMSaleTradePacket *result = topModel.data;
                NSArray *sList = result.items;
                [self.dataList removeAllObjects];
                [self.dataList addObjectsFromArray:sList];
                [self reloadData];
                
                if (self.dataList.count != 0) {
                    [self fetchStockDetailInfo];
                }
                _unShowErrorFlag=NO;
            }
            else{
                if (!_unShowErrorFlag) {
                    if (self.dataList.count == 0) {
                        [_resultView syncStatusWithError:[NSError yz_errorWithMessage:topModel.resultMessage]];
                        self.mj_header = nil;
                    }else{
                        [topModel showMessage];
                    }
                }
                self.unShowErrorFlag = YES;
            }
        } failure:^(NSError *error) {
            [self endRefresh];
            if (!_unShowErrorFlag) {
                //网络异常处理
                if (self.dataList.count == 0) {
                    [_resultView syncStatusWithError:error];
                    self.mj_header = nil;
                }else{
                    [error yz_showMessage];
                }
            }
            self.unShowErrorFlag = YES;
        }];
    }
    else{
        
        [YZClient oneY_getSaleListMemcaWithParamsuccess:^(NSURLSessionDataTask *task, id responseObject) {
            [self endRefresh];
            self.mj_header = _refreshHeader;
            self.resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
            
            YZGeneralResultModel *topModel = responseObject;
            if (topModel.success) {
                YZMSaleTradePacket *result = topModel.data;
                NSArray *sList = result.items;
                [self.dataList removeAllObjects];
                [self.dataList addObjectsFromArray:sList];
                [self reloadData];
                if (self.dataList.count != 0) {
                    [self fetchStockDetailInfo];
                }
                _unShowErrorFlag=NO;
            }else{
                if (!_unShowErrorFlag) {
                    if (self.dataList.count == 0) {
                        [_resultView syncStatusWithError:[NSError yz_errorWithMessage:topModel.resultMessage]];
                        self.mj_header = nil;
                    }else{
                        [topModel showMessage];
                    }
                }
                self.unShowErrorFlag = YES;
            }
        } failure:^(NSError *error) {
            [self endRefresh];
            if (!_unShowErrorFlag) {
                //网络异常处理
                if (self.dataList.count == 0) {
                    [_resultView syncStatusWithError:error];
                    self.mj_header = nil;
                }else{
                    [error yz_showMessage];
                }
            }
            self.unShowErrorFlag = YES;
        }];
    }
    self.firstFetchFlag = NO;
}

- (void)fetchItemListforFreeExperience{
    if (kNetworkNotReachability) {
        [self endRefresh];
        if ( self.dataList.count == 0) {
            self.resultView.status = YZM_RESULT_STATUS_FOR_NO_WIFI;
            self.mj_header = nil;
            
        }else{
            [NSError yz_showMessageForNoWifi];
            
        }
        return;
    }
    [YZClient freeEx_getSaleListFirstWithParamsuccess:^(NSURLSessionDataTask *task, id responseObject) {
        [self endRefresh];
        self.mj_header = _refreshHeader;
        self.resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
                NSArray *sList = topModel.data;
                [self.dataList removeAllObjects];
                [self.dataList addObjectsFromArray:sList];
                [self reloadData];
                if (self.dataList.count != 0) {
                    [self fetchStockDetailInfo];
                }
                _unShowErrorFlag=NO;
        }else{
            if (!_unShowErrorFlag) {
                if (self.dataList.count == 0) {
                    [_resultView syncStatusWithError:[NSError yz_errorWithMessage:topModel.resultMessage]];
                    self.mj_header = nil;
                }else{
                    [topModel showMessage];
                }
            }
            self.unShowErrorFlag = YES;
        }
    } failure:^(NSError *error) {
        [self endRefresh];
        if (!_unShowErrorFlag) {
            //网络异常处理
            if (self.dataList.count == 0) {
                [_resultView syncStatusWithError:error];
                self.mj_header = nil;
            }else{
                [error yz_showMessage];
            }
        }
        self.unShowErrorFlag = YES;
    }];
    
}



- (void)fetchItemListforSimulate{
    /*无网处理*/
    if (kNetworkNotReachability) {
        [self endRefresh];
        if ( self.dataList.count == 0) {
            self.resultView.status = YZM_RESULT_STATUS_FOR_NO_WIFI;
            self.mj_header = nil;
        }else{
            [NSError yz_showMessageForNoWifi];
        }
        return;
    }
    if (self.firstFetchFlag) {
        [YZClient simU_getSaleListFirstDataSuccess:^(NSURLResponse *response, id responseObject) {
            [self endRefresh];
            self.mj_header = _refreshHeader;
            self.resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
            
            YZGeneralResultModel *topModel = responseObject;
            if (topModel.success) {
                
                NSArray *array =  topModel.data;
                [self.dataList removeAllObjects];
                for (NSDictionary *dic in array) {
                    YZMSaleTradeModel *model=  (YZMSaleTradeModel *)dic;
                    [self.dataList addObject:model];
                }
                
                [self reloadData];
                
                if (self.dataList.count != 0) {
                    [self fetchStockDetailInfo];
                }
                _unShowErrorFlag=NO;
            }
            else{
                if (!_unShowErrorFlag) {
                    if (self.dataList.count == 0) {
                        [_resultView syncStatusWithError:[NSError yz_errorWithMessage:topModel.resultMessage]];
                        self.mj_header = nil;
                    }else{
                        [topModel showMessage];
                    }
                }
                self.unShowErrorFlag = YES;
            }
        } failure:^(NSError *error) {
            [self endRefresh];
            if (!_unShowErrorFlag) {
                //网络异常处理
                if (self.dataList.count == 0) {
                    [_resultView syncStatusWithError:error];
                    self.mj_header = nil;
                }else{
                    [error yz_showMessage];
                }
            }
            self.unShowErrorFlag = YES;
        }];
    }
    else{
        
        [YZClient simU_getSaleListFromMemcaDataSuccess:^(NSURLResponse *response, id responseObject) {
            [self endRefresh];
            self.mj_header = _refreshHeader;
            self.resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
            
            YZGeneralResultModel *topModel = responseObject;
            if (topModel.success) {
                NSArray *array =  topModel.data;
                [self.dataList removeAllObjects];
                for (NSDictionary *dic in array) {
                    YZMSaleTradeModel *model=  (YZMSaleTradeModel *)dic;
                    [self.dataList addObject:model];
                }
                [self reloadData];
                if (self.dataList.count != 0) {
                    [self fetchStockDetailInfo];
                }
                _unShowErrorFlag=NO;
            }else{
                if (!_unShowErrorFlag) {
                    if (self.dataList.count == 0) {
                        [_resultView syncStatusWithError:[NSError yz_errorWithMessage:topModel.resultMessage]];
                        self.mj_header = nil;
                    }else{
                        [topModel showMessage];
                    }
                }
                self.unShowErrorFlag = YES;
            }
        } failure:^(NSError *error) {
            [self endRefresh];
            if (!_unShowErrorFlag) {
                //网络异常处理
                if (self.dataList.count == 0) {
                    [_resultView syncStatusWithError:error];
                    self.mj_header = nil;
                }else{
                    [error yz_showMessage];
                }
            }
            self.unShowErrorFlag = YES;
        }];
    }
    self.firstFetchFlag = NO;
}

- (void)fetchStockDetailInfo{
    if (kNetworkNotReachability) {
        [self endRefresh];
        return;
    }

    NSMutableArray *array = [NSMutableArray array];
    for (YZMSaleTradeModel *stock in self.dataList) {
        [array addObject: stock.stockCode];
    }

    if (array.count == 0) {
        return;
    }
    
    [YZClient qt_getRealtimeInfoWithStockCodes:array success:^(NSURLResponse *response, id responseObject) {
        YZGeneralResultModel *topModel = responseObject;
        if(topModel.success){
            [self.realDataDict removeAllObjects];
            [self.realDataDict addEntriesFromDictionary:topModel.data];
            
            if (self.tradeType ==YZM_TRADE_TYPE_FOR_A_STOCK_D) {
                
                self.bottomValue = 0;
                for (int i=0; i<self.dataList.count; i++) {
                    
                    YZMSaleTradeModel *saleModel=self.dataList[i];
                    YZMStockRealModel *model=self.realDataDict[[NSString stringWithFormat:@"%@",saleModel.stockCode]];
                    if (saleModel.status>=4) {
                        if (!model.isSuspended) {
                            self.bottomValue += (model.price-saleModel.buyPriceDeal)*saleModel.holdCount;
                        }else{
                            self.bottomValue += (model.lastClosePrice-saleModel.buyPriceDeal)*saleModel.holdCount;
                        }
                    }
                }
                [self getbottomValue:@(self.bottomValue)];
            }
            [self reloadData];
            self.unShowErrorFlag = NO;
        }else{
            if (!_unShowErrorFlag) {
                [topModel showMessage];
            }
            self.unShowErrorFlag=YES;
        }
    } failure:^(NSError *error) {
        if (!_unShowErrorFlag) {
            [error yz_showMessage];
        }
        self.unShowErrorFlag = YES;
    }];
}


-(void)getbottomValue:(NSNumber *)bottomValue {
    
    NSMutableAttributedString *textString = nil;
    NSString *bottomStr = nil;
    NSString *valueStr = bottomValue.r4fString;
    if ([bottomValue isGreaterThanDouble:0]) {
        bottomStr = [NSString stringWithFormat:@"持仓盈亏：+%@",bottomValue.r4fString];
        textString=[[NSMutableAttributedString alloc]initWithString:bottomStr];
        [textString addAttribute:NSForegroundColorAttributeName value:[YZMAppStyle colorForRiseText] range:NSMakeRange(5, valueStr.length + 1)];
    } else if ([bottomValue isEqualWithDouble:0]) {
        
        bottomStr = [NSString stringWithFormat:@"持仓盈亏：%@",bottomValue.r4fString];
        textString=[[NSMutableAttributedString alloc]initWithString:bottomStr];
        [textString addAttribute:NSForegroundColorAttributeName value:[YZMAppStyle colorForRiseText] range:NSMakeRange(5, valueStr.length)];
    } else {
        bottomStr = [NSString stringWithFormat:@"持仓盈亏：%@",bottomValue.r4fString];
        textString=[[NSMutableAttributedString alloc]initWithString:bottomStr];
        [textString addAttribute:NSForegroundColorAttributeName value:[YZMAppStyle colorForDropText] range:NSMakeRange(5, valueStr.length)];
    }
    
    _bottomLabel.attributedText = textString;
}

#pragma mark -- timer

- (void)dataUpdate{
    if (kNetworkNotReachability) {
        [self endRefresh];
        if (!self.unShowErrorFlag) {
            self.unShowErrorFlag = YES;
            [MBProgressHUD showMessage:@"网络无法连接，无法刷新列表数据"];
        }
        return;
    }
    
    if (!YZMUserServiceInstance.isValidate) {
        if (self.dataList.count == 0) {
            self.resultView.status = YZM_RESULT_STATUS_FOR_ABNORMAL;
        }else{
            [NSError yz_showMessageForNoWifi];
        }
        return;
    }
    
    if (!self.firstFetchFlag && ![self.service isInTradeTimePeriods]) {
        if (self.inTimeFlag) {
            self.inTimeFlag = NO;
            [self reloadData];
        }
        
        //非交易时段，仍需要刷新递延费的显示情况
        if ( ![@(self.totalMoney) isGreaterThanDouble:0.0] || !self.service.isInTradeShowTimePeriods) {
            if (self.inTimeShowFlag) {
                self.inTimeShowFlag = NO;
                [self beginUpdates];
                [self reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
                [self endUpdates];
            }
        }
    }else{
        self.inTimeFlag = YES;
        
        switch (self.tradeType) {
            case YZM_TRADE_TYPE_FOR_A_STOCK:
                [self fetchItemList];
                break;
            case YZM_TRADE_TYPE_FOR_A_STOCK_YLB:
                [self fetchItemYlbList];
                break;
                
            case YZM_TRADE_TYPE_FOR_A_STOCK_D:
                [self fetchItemListforD];
                break;

            case YZM_TRADE_TYPE_FOR_A_STOCK_ONE:
                [self fetchItemListforOneYuan];
                break;

            case YZM_TRADE_TYPE_FOR_A_STOCK_SIM:
                [self fetchItemListforSimulate];
                break;
            case YZM_TRADE_TYPE_FOR_A_STOCK_FREE:
                [self fetchItemListforFreeExperience];
                break;
                
            default:
                break;
        }
    }
}

- (void)startTimer
{
    if (self.timer == nil) {
        self.firstFetchFlag = YES;
        self.timer = [NSTimer timerWithTimeInterval: 3.0 target:self selector: @selector(dataUpdate) userInfo: nil repeats: YES];
        [[NSRunLoop mainRunLoop] addTimer: self.timer forMode: NSRunLoopCommonModes];
        [self.timer fire];
    }
}

- (void)stopTimer
{
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
        self.bottomLabel.hidden = YES;
    }
}

#pragma mark -- action
- (void)buyStockPressed {
    
    YZMStockViewController *tradeVC = nil;
    switch (self.tradeType) {
        case YZM_TRADE_TYPE_FOR_A_STOCK:
            tradeVC = [YZMHCMInstance instanceWithControllerName:@"stock"];
            [tradeVC showEntrustListPage];
            break;
            
        case YZM_TRADE_TYPE_FOR_A_STOCK_D:
            tradeVC = [YZMHCMInstance instanceWithControllerName:@"stockTD"];
            [tradeVC showEntrustListPage];
            break;
            
        case YZM_TRADE_TYPE_FOR_A_STOCK_ONE:{
            YZMOneyuanViewController *oneVC = [YZMHCMInstance instanceWithControllerName:@"oneYuan"];
            [oneVC showEntrustListPage];}
            break;
            
        case YZM_TRADE_TYPE_FOR_A_STOCK_SIM:{
            YZMSimulateViewController *simVC = [YZMHCMInstance instanceWithControllerName:@"Simulate"];
            [simVC showEntrustListPage];}
            break;
        case YZM_TRADE_TYPE_FOR_A_STOCK_FREE:{
            YZMFreeExperienceViewController *freeVc = [YZMHCMInstance instanceWithControllerName:@"freeExperience"];
            [freeVc showEntrustListPage];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark -- TableView DataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.dataList.count == 0) {
        YZMStockSellNoneCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMStockSellNoneCellID forIndexPath:indexPath];
        __weak __typeof(&*self) weakSelf = self;
        cell.addAction = ^(){
            [weakSelf buyStockPressed];
        };
        return cell;
    }
    if (_tradeType==YZM_TRADE_TYPE_FOR_A_STOCK || _tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
        YZMStockSellCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMStockSellCellID forIndexPath:indexPath];
        
        cell.tradeType=self.tradeType;
        YZMSaleTradeModel *record = self.dataList[indexPath.section];
        YZMStockRealModel *recordReal = self.realDataDict[[NSString stringWithFormat:@"%@", record.stockCode]];
        cell.record = record;
        cell.realRecord = recordReal;
        
        cell.agreementAction = ^(){
            if (!YZMUserServiceInstance.isValidate) {
                [MBProgressHUD showMessage:@"网络恢复中，请稍后重试"];
                return;
            }
            [YZMWebViewService openCooperationDelegateWithTradeID:record.tid withType:self.tradeType];
        };
        cell.oweAction = ^(){
            YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:[NSString stringWithFormat:@"已逾期递延费：%@元。请尽快补缴，以免策略被接管。", @(record.owedMoney).r2fString]];
            [alertView showInView:[YZMHCMInstance currentNavationCtroller].view];
        };
        
        __weak __typeof(&*self) weakSelf = self;
        cell.sellAction = ^(){
            YZMAlertView *alertView = [weakSelf alertViewForStockSellMakeSureWithStock:record  andStockReal:recordReal andClickAction:^(BOOL selectedFlag){
                [weakSelf submitSaleTradeWithRecord:record andDelayFlag:selectedFlag];
            }];
            [alertView showInView:[YZMHCMInstance currentNavationCtroller].view];
        };

        cell.giveupBlock=^(){
            YZMAlertView *alertview = [YZMAlertView sellStopwithTitle:@"停牌股票放弃" withFirstString:@"停牌股票名称:" firstValue:record.stockName secondString:@"停牌前股票市值:" secondValue:@(recordReal.lastClosePrice*record.sumCount) thirdString:@"放弃履约保证金:" thirdValue:@(record.lossPrincipal) info:@"注：放弃停牌股票保证金不做退还"];
            alertview.ruleBlock = ^(){
                
                [YZMWebViewService openTradeRule:self.tradeType];
            };
            alertview.confirmHandle=^(){
                
                NSMutableDictionary *dic=[[NSMutableDictionary alloc]initWithObjects:@[@(record.tid),@(1),@(record.lossPrincipal).r2fString] forKeys:@[@"id",@"isTakeOver",@"lossPrincipal"]];
                [YZClient td_StopGiveUpWithParams:dic success:^(NSURLSessionDataTask *task, id responseObject) {
                    YZGeneralResultModel *topModel = responseObject;
                    if (topModel.success) {
                        [MBProgressHUD showMessage:@"放弃成功"];
                    }else{
                        [MBProgressHUD showMessage:topModel.resultMessage];
                    }
                } failure:^(NSError *error) {
                    [error yz_showMessage];
                }];
                return YES;
            };
            [alertview showInView:[YZMHCMInstance currentNavationCtroller].view];
        };

        cell.buyoverBlock=^(){
            [YZMDelayCharge showDelayChargeViewWithConfirmHandle:^BOOL{
                [weakSelf buyOutWithRecord:record recordReal:recordReal];
                return YES;
            } cancleHandle:nil noWaitPayHandle:^{
                [weakSelf buyOutWithRecord:record recordReal:recordReal];
            }];
        };
        
        return cell;
    }else if(self.tradeType==YZM_TRADE_TYPE_FOR_A_STOCK_D){
        YZMStockSellNewCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMStockSellNewCellID forIndexPath:indexPath];
        cell.tradeType=self.tradeType;
        
        YZMSaleTradeModel *record = self.dataList[indexPath.section];
        YZMStockRealModel *recordReal = self.realDataDict[[NSString stringWithFormat:@"%@", record.stockCode]];
        cell.record = record;
        cell.realRecord = recordReal;
        cell.agreementAction = ^(){
            if (!YZMUserServiceInstance.isValidate) {
                [MBProgressHUD showMessage:@"网络恢复中，请稍后重试"];
                return;
            }
            [YZMWebViewService openCooperationDelegateWithTradeID:record.tid withType:self.tradeType];
        };
        cell.oweAction = ^(){
            YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:[NSString stringWithFormat:@"已逾期递延费：%@元。请尽快补缴，以免策略被接管。", @(record.owedMoney).r2fString]];
            [alertView showInView:[YZMHCMInstance currentNavationCtroller].view];
        };
        
        __weak __typeof(&*self) weakSelf = self;
        cell.sellAction = ^(){
            YZMAlertView *alertView = [weakSelf alertViewForStockSellMakeSureWithStock:record  andStockReal:recordReal andClickAction:^(BOOL selectedFlag){
                
                [weakSelf submitSaleTradeWithRecord:record andDelayFlag:selectedFlag];
            }];
            [alertView showInView:[YZMHCMInstance currentNavationCtroller].view];
        };
        
        cell.giveupBlock=^(){
            YZMAlertView *alertview = [YZMAlertView sellStopwithTitle:@"停牌股票放弃" withFirstString:@"停牌股票名称:" firstValue:record.stockName secondString:@"停牌前股票市值:" secondValue:@(recordReal.lastClosePrice*record.sumCount) thirdString:@"放弃履约保证金:" thirdValue:@(record.buyMoney/(self.schemeModel.leverRatio+1)) info:@"注：放弃停牌股票保证金不做退还"];
            alertview.ruleBlock = ^(){
                
                [YZMWebViewService openTradeRule:self.tradeType];
            };
            alertview.confirmHandle=^(){
                
                NSMutableDictionary *dic=[[NSMutableDictionary alloc]initWithObjects:@[@(record.tid),@(1),@(record.buyMoney/(self.schemeModel.leverRatio+1)).r2fString] forKeys:@[@"id",@"isTakeOver",@"lossPrincipal"]];
                [YZClient td_StopGiveUpWithParams:dic success:^(NSURLSessionDataTask *task, id responseObject) {
                    YZGeneralResultModel *topModel = responseObject;
                    if (topModel.success) {
                        [MBProgressHUD showMessage:@"放弃成功"];
                    }else{
                        [MBProgressHUD showMessage:topModel.resultMessage];
                    }
                } failure:^(NSError *error) {
                    [error yz_showMessage];
                }];
                return YES;
            };
            [alertview showInView:[YZMHCMInstance currentNavationCtroller].view];
        };
        cell.buyoverBlock=^(){
            [YZMDelayCharge showDelayChargeViewWithConfirmHandle:^BOOL{
                [weakSelf buyOutWithDRecord:record recordReal:recordReal];
                return YES;
            } cancleHandle:nil noWaitPayHandle:^{
                [weakSelf buyOutWithDRecord:record recordReal:recordReal];
            }];
            
        };
        return cell;
    }else if(self.tradeType==YZM_TRADE_TYPE_FOR_A_STOCK_ONE){
        YZMStockSellNewCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMStockSellNewCellID forIndexPath:indexPath];
        
        cell.tradeType=self.tradeType;
        YZMSaleTradeModel *record = self.dataList[indexPath.section];
        YZMStockRealModel *recordReal = self.realDataDict[[NSString stringWithFormat:@"%@", record.stockCode]];
        cell.record = record;
        cell.realRecord = recordReal;
        
        cell.agreementAction = ^(){
            if (!YZMUserServiceInstance.isValidate) {
                [MBProgressHUD showMessage:@"网络恢复中，请稍后重试"];
                return;
            }
            [YZMWebViewService openCooperationDelegateWithTradeID:record.tid withType:self.tradeType];
        };
        cell.oweAction = ^(){
            YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:[NSString stringWithFormat:@"已逾期递延费：%@元。请尽快补缴，以免策略被接管。", @(record.owedMoney).r2fString]];
            [alertView showInView:[YZMHCMInstance currentNavationCtroller].view];
        };
        
        __weak __typeof(&*self) weakSelf = self;
        cell.sellAction = ^(){
            YZMAlertView *alertView = [weakSelf alertViewForStockSellMakeSureWithStock:record  andStockReal:recordReal andClickAction:^(BOOL selectedFlag){
                selectedFlag=NO;
                [weakSelf submitSaleTradeForOneYuanWithRecord:record andDelayFlag:selectedFlag];
            }];
            [alertView showInView:[YZMHCMInstance currentNavationCtroller].view];
        };
        
        return cell;
    }else if (self.tradeType==YZM_TRADE_TYPE_FOR_A_STOCK_SIM){
        YZMStockSellCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMStockSellCellID forIndexPath:indexPath];
        cell.tradeType=self.tradeType;
        YZMSaleTradeModel *record = self.dataList[indexPath.section];
        YZMStockRealModel *recordReal = self.realDataDict[[NSString stringWithFormat:@"%@", record.stockCode]];
        cell.record = record;
        cell.realRecord = recordReal;
        cell.agreementAction = ^(){
            if (!YZMUserServiceInstance.isValidate) {
                [MBProgressHUD showMessage:@"网络恢复中，请稍后重试"];
                return;
            }
            [YZMWebViewService openCooperationDelegateWithTradeID:record.tid withType:self.tradeType];
        };
        cell.oweAction = ^(){
            YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:[NSString stringWithFormat:@"已逾期递延费：%@元。请尽快补缴，以免策略被接管。", @(record.owedMoney).r2fString]];
            [alertView showInView:[YZMHCMInstance currentNavationCtroller].view];
        };
        
        __weak __typeof(&*self) weakSelf = self;
        cell.sellAction = ^(){
            YZMAlertView *alertView = [weakSelf alertViewForStockSellMakeSureWithStock:record  andStockReal:recordReal andClickAction:^(BOOL selectedFlag){
                [weakSelf submitSaleTradeForSimUlateWithRecord:record andDelayFlag:selectedFlag];
            }];
            [alertView showInView:[YZMHCMInstance currentNavationCtroller].view];
        };
        return cell;
    }else if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_FREE){
        YZMStockSellNewCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMStockSellNewCellID forIndexPath:indexPath];
        
        cell.tradeType=self.tradeType;
        YZMSaleTradePacket *record = self.dataList[indexPath.section];
         YZMStockRealModel *recordReal = self.realDataDict[[NSString stringWithFormat:@"%@", record.stockCode]];
        cell.realRecord = recordReal;
        cell.tradePacket = record;
        cell.agreementAction = ^(){
            if (!YZMUserServiceInstance.isValidate) {
                [MBProgressHUD showMessage:@"网络恢复中，请稍后重试"];
                return;
            }
//            [YZMWebViewService openCooperationDelegateWithTradeID:record.tid withType:self.tradeType];
        };
        cell.oweAction = ^(){
//            YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:[NSString stringWithFormat:@"已逾期递延费：%@元。请尽快补缴，以免策略被接管。", @(record.owedMoney).r2fString]];
//            [alertView showInView:[YZMHCMInstance currentNavationCtroller].view];
        };
        
        __weak __typeof(&*self) weakSelf = self;
        cell.sellAction = ^(){
            YZMAlertView *alertView = [weakSelf alertViewForStockSellMakeSureWithStockTradePacket:record andStockReal:recordReal andClickAction:^(BOOL selectedFlag){
                selectedFlag=NO;
                [weakSelf submitSaleTradeForFreeExperienceWithRecord:record];
            }];
            [alertView showInView:[YZMHCMInstance currentNavationCtroller].view];
        };
        
        return cell;
    }
    return nil;
}

//买断 T+1 A股
- (void)buyOutWithRecord:(YZMSaleTradeModel *)record recordReal:(YZMStockRealModel *)recordReal{
    NSMutableDictionary *Dic=[NSMutableDictionary dictionaryWithObject:@(record.tid) forKey:@"id"];
    [YZClient td_GetDeferDataWithdic:Dic Success:^(NSURLSessionDataTask *task, id responseObject) {
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            double deferValueData=[topModel.data doubleValue];
            [self buyoverWithrecord:record withrecordReal:recordReal withDefer:deferValueData];
        } else {
            [MBProgressHUD showMessage:topModel.resultMessage];
        }
    } failure:^(NSError *error) {
        [error yz_showMessage];
    }];

}

////买断 T+D A股
- (void)buyOutWithDRecord:(YZMSaleTradeModel *)record recordReal:(YZMStockRealModel *)recordReal{
    YZMAlertView *alertview = [YZMAlertView sellStopwithTitle:@"停牌股票买断" withFirstString:@"停牌股票名称:" firstValue:record.stockName secondString:@"停牌前股票市值:" secondValue:@(recordReal.lastClosePrice*record.sumCount) thirdString:@"买断费用:" thirdValue:@(record.buyMoney)];
    alertview.ruleBlock = ^(){
        
        [YZMWebViewService openTradeRule:self.tradeType];
    };
    alertview.confirmHandle=^(){
        NSMutableDictionary *dic=[[NSMutableDictionary alloc]initWithObjects:@[@(record.tid),@(2),@(record.buyMoney).r2fString] forKeys:@[@"id",@"isTakeOver",@"lossPrincipal"]];
        [YZClient td_StopBuyOverWithParams:dic success:^(NSURLSessionDataTask *task, id responseObject) {
            YZGeneralResultModel *topModel = responseObject;
            if (topModel.success) {
                [MBProgressHUD showMessage:@"买断成功"];
            } else {
                [MBProgressHUD showMessage:topModel.resultMessage];
            }
        } failure:^(NSError *error) {
            [error yz_showMessage];
        }];
        return YES;
    };
    [alertview showInView:[YZMHCMInstance currentNavationCtroller].view];
}

- (void)submitSaleTradeWithRecord:(YZMSaleTradeModel *)record andDelayFlag:(BOOL)delayFlag{
    
    if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
        [self requestCloseTradeYlbWithRecord:record andDelayFlag:delayFlag];
        return;
    }
    [YZClient td_closeTradeWithID:record.tid andAlwaysCloseFlag:delayFlag success:^(NSURLResponse *response, id responseObject) {
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            YZMSaleTradeModel *stock = [record copy];
            stock.status = YZMSaleTradeStausForToClose;
            [self.dataList replaceObjectAtIndex:[self.dataList indexOfObject:record] withObject:stock];
            [self reloadData];
            [MBProgressHUD showMessage:@"点卖委托成功"];
        }else{
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        [error yz_showMessage];
    }];
}

- (void)requestCloseTradeYlbWithRecord:(YZMSaleTradeModel *)record andDelayFlag:(BOOL)delayFlag{
    [YZClient td_closeTradeYlbWithID:record.tid andAlwaysCloseFlag:delayFlag success:^(NSURLResponse *response, id responseObject) {
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            YZMSaleTradeModel *stock = [record copy];
            stock.status = YZMSaleTradeStausForToClose;
            [self.dataList replaceObjectAtIndex:[self.dataList indexOfObject:record] withObject:stock];
            [self reloadData];
            [MBProgressHUD showMessage:@"点卖委托成功"];
        }else{
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        [error yz_showMessage];
    }];
}


- (void)submitSaleTradeForOneYuanWithRecord:(YZMSaleTradeModel *)record andDelayFlag:(BOOL)delayFlag{
    
    [YZClient oneY_closeTradeWithID:record.tid andAlwaysCloseFlag:delayFlag success:^(NSURLResponse *response, id responseObject) {
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            YZMSaleTradeModel *stock = [record copy];
            stock.status = YZMSaleTradeStausForToClose;
            [self.dataList replaceObjectAtIndex:[self.dataList indexOfObject:record] withObject:stock];
            [self reloadData];
            [MBProgressHUD showMessage:@"点卖委托成功"];
        }else{
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
         [error yz_showMessage];
    }];
}

- (void)submitSaleTradeForFreeExperienceWithRecord:(YZMSaleTradePacket *)record{
    
    [YZClient freeEx_closeTradeWithID:record.strategyId  success:^(NSURLResponse *response, id responseObject) {
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            YZMSaleTradeModel *stock = [record copy];
            stock.status = YZMSaleTradeStausForToClose;
            [self.dataList replaceObjectAtIndex:[self.dataList indexOfObject:record] withObject:stock];
            [self reloadData];
            [MBProgressHUD showMessage:@"点卖委托成功"];
        }else{
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        [error yz_showMessage];
    }];
}

-(void)buyoverWithrecord:(YZMSaleTradeModel *)record withrecordReal:(YZMStockRealModel *)recordReal withDefer:(float )deferData{
    
    YZMAlertView *alertview;
    if ([@(deferData) isEqualWithDouble:0]) {
//        if (record.buyPriceDeal>recordReal.lastClosePrice) {
//            alertview=[YZMAlertView sellStopwithTitle:@"停牌股票买断" withFirstString:@"停牌股票名称:" firstValue:record.stockName secondString:@"停牌前股票市值:" secondValue:@(recordReal.lastClosePrice*record.sumCount) thirdString:@"买断费用:" thirdValue:@(record.buyPriceDeal*record.holdCount+(record.buyPriceDeal-recordReal.lastClosePrice)*record.holdCount) withLossValue:@(record.lossPrincipal)];
//                       
//            
//        }else{
            alertview=[YZMAlertView sellStopwithTitle:@"停牌股票买断" withFirstString:@"停牌股票名称:" firstValue:record.stockName secondString:@"停牌前股票市值:" secondValue:@(recordReal.lastClosePrice*record.sumCount) thirdString:@"买断费用:" thirdValue:@(record.buyPriceDeal*record.holdCount) withLossValue:@(record.lossPrincipal)];
        
//        }
    }else{
//        if (record.buyPriceDeal>recordReal.lastClosePrice) {
//            alertview=[YZMAlertView sellStopwithotherTitle:@"停牌股票买断" withFirstString:@"停牌股票名称:" firstValue:record.stockName secondString:@"停牌前股票市值:" secondValue:@(recordReal.lastClosePrice*record.sumCount) thirdString:@"买断费用:" thirdValue:@(record.buyPriceDeal*record.holdCount+(record.buyPriceDeal-recordReal.lastClosePrice)*record.holdCount+deferData) withdeferValue:@(deferData) withLossValue:@(record.lossPrincipal)];
//        }else{
            alertview=[YZMAlertView sellStopwithotherTitle:@"停牌股票买断" withFirstString:@"停牌股票名称:" firstValue:record.stockName secondString:@"停牌前股票市值:" secondValue:@(recordReal.lastClosePrice*record.sumCount) thirdString:@"买断费用:" thirdValue:@(record.buyPriceDeal*record.holdCount+deferData) withdeferValue:@(deferData) withLossValue:@(record.lossPrincipal)];
//        }
    }
    
    alertview.ruleBlock = ^(){
        
        [YZMWebViewService openTradeRule:self.tradeType];
    };
    
    alertview.confirmHandle=^(){
        NSMutableDictionary *dic=[[NSMutableDictionary alloc]initWithObjects:@[@(record.tid),@(2),@(recordReal.lastClosePrice*record.holdCount+deferData).r2fString] forKeys:@[@"id",@"isTakeOver",@"lossPrincipal"]];
        [YZClient td_StopBuyOverWithParams:dic success:^(NSURLSessionDataTask *task, id responseObject) {
            YZGeneralResultModel *topModel = responseObject;
            if (topModel.success) {
                [MBProgressHUD showMessage:@"买断成功"];
            } else {
                [MBProgressHUD showMessage:topModel.resultMessage];
            }
        } failure:^(NSError *error) {
            [error yz_showMessage];
        }];
        return YES;
    };
    [alertview showInView:[YZMHCMInstance currentNavationCtroller].view];
}

- (void)submitSaleTradeForSimUlateWithRecord:(YZMSaleTradeModel *)record andDelayFlag:(BOOL)delayFlag{
    
    [YZClient simU_closeTradeWithID:record.tid andAlwaysCloseFlag:delayFlag success:^(NSURLResponse *response, id responseObject) {
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            YZMSaleTradeModel *stock = [record copy];
            stock.status = YZMSaleTradeStausForToClose;
            [self.dataList replaceObjectAtIndex:[self.dataList indexOfObject:record] withObject:stock];
            [self reloadData];
            [MBProgressHUD showMessage:@"点卖委托成功"];
        }else{
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        [error yz_showMessage];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataList.count?self.dataList.count:1;
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (self.tradeType) {
        case YZM_TRADE_TYPE_FOR_A_STOCK:{
            if (self.dataList.count == 0) {
                return self.frame.size.height - self.tableHeaderView.frame.size.height - 50;
            }else{
                YZMSaleTradeModel *model=self.dataList[indexPath.section];
                return [YZMStockSellCell heightWithRecord:model];
            }
        }
            break;
            
        case YZM_TRADE_TYPE_FOR_A_STOCK_D:
            if (self.dataList.count == 0) {
                return self.frame.size.height - self.tableHeaderView.frame.size.height - 50;
            }else{
                return 184;
            }
            break;
        case YZM_TRADE_TYPE_FOR_A_STOCK_YLB:
            if (self.dataList.count == 0) {
                return self.frame.size.height - self.tableHeaderView.frame.size.height - 50;
            }else{
                YZMSaleTradeModel *model=self.dataList[indexPath.section];
                return [YZMStockSellCell heightWithRecord:model];
            }
            break;
            break;
        case YZM_TRADE_TYPE_FOR_A_STOCK_ONE:
        case YZM_TRADE_TYPE_FOR_A_STOCK_FREE:
        case YZM_TRADE_TYPE_FOR_A_STOCK_SIM:
            if (self.dataList.count == 0) {
                return self.frame.size.height - self.tableHeaderView.frame.size.height - 50;
            }else{
                return 184;
            }
            break;
            
        default:
            break;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0 && self.inTimeShowFlag) {
        if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
            return 0;
        }
        return self.headerHeight;
    } else if (section == 0 && !self.inTimeShowFlag) {
        return 0;
    }
    return 14;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if ((self.tradeType!=YZM_TRADE_TYPE_FOR_A_STOCK) && section==self.dataList.count-1) {
        return 36;
    }else{
        return 0;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [[UIView alloc]init];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0 && self.inTimeShowFlag) {
        if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
            return [UIView new];
        }
        YZMStockSellHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:sYZMStockSellHeaderID];
        [header setTotalMoney:self.totalMoney andExpireMoney:self.expireMoney];
        
        return header;
    }
    return  [UIView new];
}

@end
